//
//  CEDeviceListViewController.m
//  C8 Energy
//
//  Created by 颜魏 on 2024/10/1.
//

#import "CEDeviceListViewController.h"
#import "CEDeviceListTableViewCell.h"
#import "DAConfig.h"
#import "NSBundle+DAUtils.h"
#import "CETabbarController.h"
#import "DeviceSettingViewController.h"
#import <MJRefresh/MJRefresh.h>

@interface CEDeviceListViewController ()<UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UILabel *titleLabel;
@property (weak, nonatomic) IBOutlet UIView *bgView;
@property (weak, nonatomic) IBOutlet UITextField *nameTF;
@property (weak, nonatomic) IBOutlet UIButton *searchBtn;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UILabel *addLabel;
@property (weak, nonatomic) IBOutlet UILabel *tipsLabel;

@property (nonatomic, strong) NSMutableArray<CBPeripheral *> *dataSource;
@property (nonatomic, strong) NSMutableArray<CBPeripheral *> *orgDataSource;
@property (nonatomic, strong) NSMutableArray *batteryLevelSource;
@property (nonatomic, assign) BOOL isSearch;
@property (nonatomic, assign) BOOL isPushed;
@property (nonatomic, strong) NSMutableDictionary *diviceNameDict;

@end

@implementation CEDeviceListViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBarHidden = YES;
    self.dataSource = [[NSMutableArray alloc] init];
    self.orgDataSource = [[NSMutableArray alloc] init];
    self.batteryLevelSource = [[NSMutableArray alloc] init];
    self.diviceNameDict = [[NSMutableDictionary alloc] init];
    self.isSearch = NO;
    self.isPushed = NO;
    if ([BTManager sharedBTManager].peripherals.count) {
        [self.orgDataSource addObjectsFromArray:[BTManager sharedBTManager].peripherals];
        [self.dataSource addObjectsFromArray:[BTManager sharedBTManager].peripherals];
    }
    [[BTManager sharedBTManager] startScan];

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchDevices:) name:kBTSearchDevices object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(searchDevicesName:) name:kBTSearchDevicesName object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(connectSuccess) name:kBTConnectionSucceed object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(getBatteryLevel:) name:kBTGetBatteryLevel object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloadList) name:@"RELOAD_BLUETOOTH_LIST" object:nil];

    self.bgView.layer.borderWidth = 1;
    self.bgView.layer.borderColor = RGB16(0xDEDEDE).CGColor;
    self.bgView.layer.cornerRadius = 4;
    self.bgView.layer.masksToBounds = YES;
    self.tableView.tableFooterView = [[UIView alloc] init];
    [self.tableView registerNib:[UINib nibWithNibName:@"CEDeviceListTableViewCell" bundle:nil] forCellReuseIdentifier:@"CEDeviceListTableViewCell"];
    WeakSelf
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        if (!weakSelf.isSearch && weakSelf.orgDataSource.count == weakSelf.batteryLevelSource.count) {
            weakSelf.isPushed = YES;
            [weakSelf reloadList];
        }else {
            [weakSelf.tableView.mj_header endRefreshing];
        }
    }];

    [self setLanguage];
}

- (void)reloadList {
    if (self.isPushed) {
        [[BTManager sharedBTManager] retartScan];
    }
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
//    NSString *isChangeLanguage = [[NSUserDefaults standardUserDefaults] objectForKey:IS_ChANGD_LANGUAGE];
//    if (!isChangeLanguage || isChangeLanguage.integerValue != 1) {
//        [BTManager sharedBTManager].isGettingBattery = YES;
//    }
    [self reloadList];
}

- (void)viewDidLayoutSubviews {
    self.bgView.layer.cornerRadius = 10;
    self.bgView.layer.masksToBounds = YES;
}

//- (void)viewDidDisappear:(BOOL)animated {
//    [super viewDidDisappear:animated];
//    [BTManager sharedBTManager].isGettingBattery = NO;
//}

- (void)setLanguage {
    self.titleLabel.text = NSLocalizedString(@"Connect Device", nil);
    [self.searchBtn setTitle:NSLocalizedString(@"Confirm", nil) forState:UIControlStateNormal];
    self.nameTF.placeholder = NSLocalizedString(@"Please enter device name", nil);
    self.addLabel.text = NSLocalizedString(@"Add a device", nil);
    self.tipsLabel.text = NSLocalizedString(@"Device List", nil);
}

- (void)reloadLanguage {
    [ProgressHUD showActivityMessageInView:@"" timer:2];
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        UINavigationController *nv = [[UINavigationController alloc] initWithRootViewController:[[CEDeviceListViewController alloc] initWithNibName:@"CEDeviceListViewController" bundle:nil]];
        UIWindow *window = [UIApplication sharedApplication].delegate.window;
        window.rootViewController = nv;
        [window makeKeyAndVisible];
    });
}

#pragma mark - action
- (IBAction)actionLanguage:(id)sender {
//    DeviceSettingViewController *vc = [[DeviceSettingViewController alloc] initWithNibName:@"DeviceSettingViewController" bundle:nil];
//    [self.navigationController pushViewController:vc animated:YES];
//    return;
    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:nil message:NSLocalizedString(@"Language", nil) preferredStyle:UIAlertControllerStyleActionSheet];
    [sheet addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Chinese", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [DAConfig setUserLanguage:@"zh-Hans"];
        [self reloadLanguage];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"English", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [DAConfig setUserLanguage:@"en"];
        [self reloadLanguage];
    }]];
    [sheet addAction:[UIAlertAction actionWithTitle:NSLocalizedString(@"Cancel", nil) style:UIAlertActionStyleDefault handler:nil]];
    [self presentViewController:sheet animated:YES completion:nil];
}

- (IBAction)actionSearch:(id)sender {
    [self.nameTF resignFirstResponder];
    [self startSearch];
}

- (void)startSearch {
    self.isSearch = self.nameTF.text.length>0;
    [self.dataSource removeAllObjects];
    if (self.isSearch) {
        for (CBPeripheral *peripheral in self.orgDataSource) {
            if ([peripheral.name containsString:self.nameTF.text]) {
                [self.dataSource addObject:peripheral];
            }
        }
    }else {
        [self.dataSource addObjectsFromArray:self.orgDataSource];
    }
    [self.tableView reloadData];
}

#pragma mark - notification
- (void)searchDevicesName:(NSNotification *)nf {
    NSMutableDictionary *dict = nf.object;
    [self.diviceNameDict addEntriesFromDictionary:dict];
    [self.tableView reloadData];
}

- (void)searchDevices:(NSNotification *)nf {
        NSArray *list = nf.object;
    [self.orgDataSource removeAllObjects];
    [self.orgDataSource addObjectsFromArray:list];
    [self.dataSource removeAllObjects];
    if (self.isSearch) {
        for (CBPeripheral *peripheral in self.orgDataSource) {
            if ([peripheral.name containsString:self.nameTF.text]) {
                [self.dataSource addObject:peripheral];
            }
        }
    }else {
        [self.dataSource addObjectsFromArray:self.orgDataSource];
    }
    [self.tableView.mj_header endRefreshing];
    [self.tableView reloadData];
//    if (self.orgDataSource.count) {
//        static dispatch_once_t onceToken;
//        dispatch_once(&onceToken, ^{
//            [BTManager sharedBTManager].isGettingBattery = YES;
//        });
//    }
}

- (void)getBatteryLevel:(NSNotification *)nf {
    NSArray *list = nf.object;
    [self.batteryLevelSource removeAllObjects];
    [self.batteryLevelSource addObjectsFromArray:list];
    [self.tableView reloadData];
}

- (void)connectSuccess {
    NSString *isChangeLanguage = [[NSUserDefaults standardUserDefaults] objectForKey:IS_ChANGD_LANGUAGE];
    if ((!isChangeLanguage || isChangeLanguage.integerValue != 1) && self.navigationController.childViewControllers.count==1) {
        [ProgressHUD hideHUD];
        [ProgressHUD showSuccessMessage:NSLocalizedString(@"Connected", nil)];
        self.isPushed = YES;
        CETabbarController *tabbar = [[CETabbarController alloc] init];
        [self.navigationController pushViewController:tabbar animated:YES];
    }
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:IS_ChANGD_LANGUAGE];
        [[NSUserDefaults standardUserDefaults] synchronize];
    });
}

#pragma mark - UITableViewDelegate
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSource.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CEDeviceListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CEDeviceListTableViewCell"];
    NSString *name = [self.diviceNameDict objectForKey:self.dataSource[indexPath.row].name];
    cell.nameLabel.text = name.length>0 ? name : self.dataSource[indexPath.row].name;
//    NSString *battery = @"0%";
//    for (NSInteger i=0; i<self.batteryLevelSource.count; i++) {
//        NSDictionary *dict = self.batteryLevelSource[i];
//        if ([[dict objectForKey:@"name"] isEqualToString:self.dataSource[indexPath.row].name]) {
//            if ([[dict objectForKey:@"batteryLevel"] integerValue] != -1) {
//                battery = [NSString stringWithFormat:@"%@%%", dict[@"batteryLevel"]];
//                break;
//            }
//        }
//    }
//    cell.level = battery;
    
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 65;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [ProgressHUD showActivityMessageInView:NSLocalizedString(@"Connecting", nil)];
//    [BTManager sharedBTManager].isGettingBattery = NO;
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [[BTManager sharedBTManager] connectPeripheral:self.dataSource[indexPath.row]];
    });
    [[NSUserDefaults standardUserDefaults] setObject:@"0" forKey:IS_ChANGD_LANGUAGE];
    [[NSUserDefaults standardUserDefaults] synchronize];
}

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    [self startSearch];
    
    return YES;
}


@end
